<?php
/*
 * @See Clu_Db_Table_Abstract
 */
class Model_News extends Zend_Db_Table_Abstract
{
	//only specify the table name, everything else inherits
    	protected $_name = "news";
    	protected $_primary = "id";
    
	public function findByPrimary($id)
	{
		if (!$id)
            return null;
        else
		    return $this->fetchRow('id = ' . $this->getAdapter()->quote($id, 'INTEGER'));
	}
	
	public function getNewsData($id, $getArticle = true, $mode = 'array')
	{
		$n = $this->findByPrimary($id);
		$ret = $n->toArray(); 
		$articleId = $ret['article_id'];
		$aModel = new article_Model_Service();
		$tmp = $aModel->getArticleData($ret['article_id']);
		$a = $tmp->toArray();
		$ret['body'] = $a['article_body'];
//		die_a($ret);
		return $ret;
		//die_a($ret);
	
	
	}
	public function transformToFormArray($eRow,$edit) 
	{
		$aModel = new article_Model_Service();
		$tmp = $aModel->findByPrimary($eRow['article_id']);
//		die_a($tmp);
        $Row['poster_id']  =  $tmp['article_poster_id'] ;
        $Row['post_time']  =  $tmp['article_post_time'] ;
        $Row['body']       =  $tmp['article_body'] ;
		$Row['title']	   =  $tmp['article_title'] ;
        $Row['status']     =  $tmp['article_status'] ;
        $Row['language']   =  $tmp['article_language'] ;
        $Row['keywords']   =  $tmp['article_keywords'] ;
		/*
        $keys = array('title', 'description', 'keywords',
					  'status', 'frequency');
		$Row = clu_array_merge($keys, $tmp);*/
		
		$Row['id'] 				= $eRow['id'];
		$Row['status'] 			= $eRow['status'];
		if($edit == false)
		{
    		$mCategory = new category_Model_Category();
            $mCategory->setTables('news');
            $Row['category'] = null;
            foreach($mCategory->getRootType('Root_News') as $e) {
            	foreach(explode(',', $eRow['category']) as $tmp)
                	if($e['id'] == $tmp)
                		$Row['category'] .= $e['name'].',';
            }   
		}
		else
        	$Row['category']   = explode(',', $eRow['category']);
        	
		return $Row;
	}
	public function insertRaw($data ,$doValidate = false)
	{ 
		if($doValidate)
    	{
    		$form = new Form_News();
    		if(!$form->isValid($data))
    			return false;
		}
		$n = array();
	    $n['status']        = "queued"; 
	    $n['article_id']    = $data['article_id'];
		$n['category']      = implode(',', $data['category']);
        $auth = Zend_Auth::getInstance();
	    $n['poster_id'] 	= $auth->getIdentity()->id;
        $n['post_time'] 	= time();
		
		return $this->insert($n);
	}
	
	public function saveRaw($n, $data, $id, $doValidate)
	{
	    if((!$n) && (!$id))
	    	return false;
	    else if(!$n)
	       	if(!$n = $this->findByPrimary($id))
	       		return false;

	    if ($doValidate)
	    {
	    	//Validate Data here
	    }
		$tmp = array();
//		$tmp['status'] 		= $data['status'];
		$tmp['category']    = implode(',', $data['category']);
	    $n->setFromArray($tmp);
        return $n->save();
	}
	
	public function search($data)
	{	
//	die_a($data);
		$title 			= isset($data['title'])       ? $data['title']:null;
		$category 		= isset($data['category'])    ? $data['category'] : null; 
		$status 		= isset($data['status'])      ? $data['status']:null;
     	$startDate		= isset($data['start_date'])  ? strtotime($data['start_date']) :null;
     	$finishDate		= isset($data['finish_date'])  ? strtotime($data['finish_date']) :null;
//     	die_a($startDate . $finishDate);
//     	die_a($finishDate);
		//select SQL query
    	$db = $this->getAdapter();
		$select = $db->select()
				     ->distinct();
		
		// Add a FROM clause
        $select->from( array('n' => 'news'));
        $select->from( array('a' => 'articles'), '');
        
        if($title)
            $select->where('a.article_title LIKE ?',$db->quoteinto("%$title%","STRING"))
            		->where('a.article_id = n.article_id');
        if($status && $status != 'all')
    		$select->where('n.status = ?', $db->quoteinto($status,'STRING'));
    	
	 	if($category)
        {
            foreach($category as $c)
                $select->orwhere($db->quoteinto("find_in_set(?,n.category)", $c));
        }
        if($startDate)
        	$select->where('n.post_time >= ?', $db->quote($startDate,'INTEGER'));
        if($finishDate)
        	$select->where('n.post_time <= ?', $db->quote($finishDate,'INTEGER'));
        

    	
//    	die($select);
        return $select;
	}
	
	public function deleteByPrimary($idArray, $atomic = true)
	{
       	$auth = Zend_Auth::getInstance();
     	$uIdentity = $auth->getIdentity();
     	$sess = new Zend_Session_Namespace(CLU_NS);
        if (!$auth->hasIdentity())
		{
		 	$this->view->errorMessage = t(310);
            $this->renderToHolder('common/error.phtml');
            return;
		}
		$aModel = new article_Model_Service();
        foreach ($idArray as $newsId)
        {
        	$tmp = $this->findByPrimary($newsId)->toArray();
        	$articleIds[]   = $tmp['article_id']; 
        	$posterIds[]	= $tmp['poster_id'];
        }        
		$auth = Zend_Auth::getInstance();
        $db = $this->getAdapter();
        
        if ($atomic)
	        $db->beginTransaction(); //@NOTE: no effect with MyISAM
	        
        if (($uIdentity->id != $db->quote($posterIds, 'INTEGER') && strpos ($sess->userPermissions, 'delete event') === false) || 
            ($uIdentity->id == $db->quote($posterIds, 'INTEGER') && strpos ($sess->userPermissions, 'delete event') === false))
        {
            return false;
        }
        else 
        {
            try
            {
                $sql = "DELETE FROM news WHERE id IN (". $db->quote($idArray, 'INTEGER') .")" ;
               	$db->query($sql);
                $aModel->deleteByPrimary($articleIds,false); //non atomic
               	if ($atomic)
    	            $db->commit();
                return true;
        	}
            catch (Exception $e)
            {
                if ($atomic)
    	            $db->rollBack();
                return false;
            }
        }
	}
	
	public function bulkUpdateStatus($idArray, $data, $atomic = true)
	{	
		$idList = implode (',', $idArray);
		$auth = Zend_Auth::getInstance();
     	$uIdentity = $auth->getIdentity();
     	$sess = new Zend_Session_Namespace(CLU_NS);
        if (!$auth->hasIdentity())
		{
		 	$this->view->errorMessage = t(311);
            $this->renderToHolder('common/error.phtml');
            return;
		}
		$aModel = new article_Model_Service();
        foreach ($idArray as $newsId)
        {
        	$tmp = $this->findByPrimary($newsId)->toArray();
        	$articleIds[]   = $tmp['article_id']; 
        	$posterIds[]	= $tmp['poster_id'];
        }       
        
        $db = $this->getAdapter();
        
        if ($atomic)
        	$db->beginTransaction(); //@NOTE: no effect with MyISAM
        
        if ( ($uIdentity->id != $db->quote($posterIds, 'INTEGER') && strpos($sess->userPermissions, 'set status news') === false) || 
            ($uIdentity->id != $db->quote($posterIds, 'INTEGER') && strpos ($sess->userPermissions, 'set status news') === false))
        {
            return false;
        }
        else 
        {
            try
            {
                $sql = "UPDATE news SET status = '".$db->quoteinto($data['status'],"STRING")."' WHERE id IN (".$idList.")" ;
               	$db->query($sql);
                $aModel->bulkUpdateStatus($articleIds,$data,false); //non atomic
                if ($atomic)
	            	$db->commit();
                return true;
        	}
            catch (Exception $e)
            {
            	if ($atomic)
	            	$db->rollBack();
                return false;
            }
        } 
	}
	
	public function getLatestRecruitments()
	{
		$db = $this->getAdapter();
        $sql = "SELECT * from news " ;
       	$ret = $db->query($sql);
       	$aModel = new article_Model_Service();
        foreach ($ret->fetchAll() as $newsId)
        {
        	$tmp[$newsId['id']] = $aModel->findByPrimary($newsId['article_id'])->toArray();
        }       
       	return $tmp;
	}
	
}
?>
